import React, { useState, useEffect } from "react"
import instance from "../../utils/instance"
import { getCookie } from "../../utils/cookie"
import "./QuestionCard.css"

function QuestionCard(props) {
    const [topic, setTopic] = useState([])
    const [title, setTitle] = useState(props.question.title)
    const [description, setDescription] = useState(props.question.description)
    const [topics, setTopics] = useState([])
    const [editActive, setEditActive] = useState(false)
    useEffect(() => {
        instance.get("/topic").then(data => {
            if (data.data.errno === 0) {
                setTopic(data.data.data)
                setTopics([data.data.data[0]._id])
            }
        })
    }, [])
    const patchQuestion = (e) => {
        let _id = props.question._id
        let token = getCookie("token")
        instance.defaults.headers.common['Authorization'] = "Bearer " + token
        instance.patch(`/question/${_id}`, {
            title,
            description,
            topics
        }).then(data => {
            if (data.data.errno === 0) {
                alert("更新内容成功！")
                window.location.reload()
            } else {
                alert("内容更新失败!")
            }
        }).catch(err => {
            alert("内容更新失败!")
        })
    }
    return (
        <div className="question_card">
            <div className="question_card_head">
                <a href={`#/question/${props.question._id}`}>{props.question.title}</a>
                <span>{props.question.updatedAt.split("T")[0]}</span>
            </div>
            <div className="question_card_content">
                <p>{props.question.description}</p>
            </div>
            {
                props.me && (<div className="edit_this_question">
                    <a href="#/user" onClick={e => { editActive ? setEditActive(false) : setEditActive(true) }}>编辑此问题</a>
                    {
                        editActive && (<div className="edit_question_form">
                            <input type="text" value={title} required onChange={e => setTitle(e.target.value)} />
                            <textarea value={description} onChange={e => setDescription(e.target.value)} />
                            {
                                topic.length > 0 ? (
                                    <select onChange={e => setTopics([e.target.value])} >
                                        {topic.map(item => {
                                            return (<option value={item._id} key={item._id}>{item.name}</option>)
                                        })}
                                    </select>
                                ) : ""
                            }
                            <input type="button" value="提交更新" onClick={(e) => { patchQuestion(e) }} />
                        </div>)
                    }
                </div>)
            }
        </div>
    )
}


export default QuestionCard